import React from 'react';
import {
    Box,
    TextField,
    Button,
    Typography,
    Paper,
    Divider,
    FormControl,
    InputLabel,
    Select,
    MenuItem,
    SelectChangeEvent
} from '@mui/material';
import { useAppContext } from '../contexts/AppContext';
import { useEthersContext } from '../contexts/EthersContext';
import { DEFAULT_NETWORKS } from '../utils/networkUtils';

const ChainConfig: React.FC = () => {
    const { state, dispatch } = useAppContext();
    const { setProvider, currentNetwork } = useEthersContext();
    const [localRpc, setLocalRpc] = React.useState(state.customRpc);

    const handleNetworkChange = (event: SelectChangeEvent<number>) => {
        const selectedChainId = Number(event.target.value);
        const selectedNetwork = state.networks.find(n => n.chainId === selectedChainId);
        if (selectedNetwork) {
            dispatch({ type: 'SET_NETWORK', payload: selectedNetwork });
            setProvider(selectedNetwork.rpcUrl);
        }
    };

    const handleCustomRpcSubmit = () => {
        if (localRpc) {
            dispatch({ type: 'SET_CUSTOM_RPC', payload: localRpc });
            setProvider(localRpc);
        }
    };

    return (
        <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
            <Typography variant="h6" gutterBottom>
                Network Configuration
            </Typography>
            <Divider sx={{ mb: 2 }} />

            <FormControl fullWidth sx={{ mb: 2 }}>
                <InputLabel id="network-select-label">Select Network</InputLabel>
                <Select
                    labelId="network-select-label"
                    value={state.currentNetwork?.chainId || ''}
                    onChange={handleNetworkChange}
                    label="Select Network"
                >
                    {state.networks.map((network) => (
                        <MenuItem key={network.chainId} value={network.chainId}>
                            {network.name} (Chain ID: {network.chainId})
                        </MenuItem>
                    ))}
                </Select>
            </FormControl>

            <Typography variant="subtitle1" gutterBottom>
                Or use custom RPC:
            </Typography>

            <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
                <TextField
                    label="Custom RPC URL"
                    variant="outlined"
                    fullWidth
                    value={localRpc}
                    onChange={(e) => setLocalRpc(e.target.value)}
                    placeholder="https://..."
                />
                <Button
                    variant="contained"
                    onClick={handleCustomRpcSubmit}
                    disabled={!localRpc}
                    sx={{ minWidth: 120 }}
                >
                    Apply
                </Button>
            </Box>

            {currentNetwork && (
                <Typography variant="body2" color="text.secondary">
                    Current Network: {currentNetwork.name} (Chain ID: {currentNetwork.chainId})
                    {currentNetwork.rpcUrl && ` | RPC: ${currentNetwork.rpcUrl}`}
                </Typography>
            )}
        </Paper>
    );
};

export default ChainConfig;